package com.qiantu.phone.ui.activity;

import android.content.Intent;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hjq.base.BaseAdapter;
import com.hjq.widget.layout.SettingBar;
import com.qiantu.api.entity.LinkageBean;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.bean.LocationData;
import com.qiantu.phone.bean.WeatherTypeBean;
import com.qiantu.api.entity.WeatherValueBean;
import com.qiantu.phone.ui.activity.map.LocationActivity;
import com.qiantu.phone.ui.adapter.WeatherTypeAdapter;
import com.qiantu.phone.ui.adapter.WeatherValueAdapter;
import com.qiantu.phone.ui.dialog.BottomCheckListDialog;
import com.qiantu.phone.utils.LinkageDataHolder;
import com.qiantu.phone.utils.WeatherConditionTypeParseUtil;
import com.lxj.xpopup.XPopup;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * time   : 2021/12/22
 */
public final class WeatherActivity extends AppActivity {

    private SettingBar settingReferenceArea;
    private TextView tvWeatherCondition;
    private RecyclerView recyclerView;
    private WeatherTypeAdapter mWeatherTypeAdapter;
    private BottomCheckListDialog mBottomCheckListDialog;
    private int mClickWeatherType;
    private SparseArray<List<WeatherValueBean>> selectedWeather = new SparseArray();
    private String serialNo;
    private String areaName;
    private String areaCoding;
    private int weatherTypeXor = -1;
    private double longitude;
    private double latitude;
    private int scopeLong;
    private List<WeatherValueBean> weatherKeyValue;
    private LinkageBean mLinkageBean;
    private LinkageBean.LinkageCondition mLinkageCondition;
    private List<WeatherTypeBean> weatherTypeList;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_weather;
    }

    @Override
    protected void initView() {
        settingReferenceArea = findViewById(R.id.setting_reference_area);
        tvWeatherCondition = findViewById(R.id.tv_weather_condition);
        recyclerView = findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mWeatherTypeAdapter = new WeatherTypeAdapter(getContext());
        weatherTypeList = WeatherConditionTypeParseUtil.parseData(getContext());
        mWeatherTypeAdapter.setData(weatherTypeList);
        recyclerView.setAdapter(mWeatherTypeAdapter);
        mWeatherTypeAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView recyclerView, View itemView, int position) {
                WeatherTypeBean weatherType = mWeatherTypeAdapter.getData().get(position);
                mClickWeatherType = weatherType.getType();
                if(weatherType.getValues().size() == 1){
                    WeatherValueBean weatherValueBean = weatherType.getValues().get(0);
                    List<WeatherValueBean> selectedWeatherValues = new ArrayList<>();
                    selectedWeatherValues.add(weatherValueBean);
                    int res = getResources().getIdentifier(weatherValueBean.getName(), "string", getContext().getPackageName());
                    String weatherName = getString(res);
                    tvWeatherCondition.setText(getString(R.string.effective_when_time_holder, weatherName));
                    selectedWeather.clear();
                    selectedWeather.put(mClickWeatherType, selectedWeatherValues);
                    mWeatherTypeAdapter.checkSelected(mClickWeatherType);
//                    mWeatherTypeAdapter.setSelectedValues(selectedWeatherValues);
                    getTitleBar().getRightView().setEnabled(true);
                }else{
                    showBottomCheckListDialog(weatherType.getValues());
                }
            }
        });
        setOnClickListener(settingReferenceArea);
        getTitleBar().getRightView().setEnabled(false);
    }

    @Override
    protected void initData() {
        serialNo = getString("serial_no");
        mLinkageBean = LinkageDataHolder.getLinkageData();
        if(mLinkageBean != null){
            List<LinkageBean.LinkageCondition> linkageConditions = mLinkageBean.getLinkageConditions();
            if(linkageConditions != null && linkageConditions.size() > 0 && !TextUtils.isEmpty(serialNo)){
                for(LinkageBean.LinkageCondition item : linkageConditions){
                    if(item.getConditionSerialNo().equals(serialNo)){
                        mLinkageCondition = item;
                        areaName = mLinkageCondition.getAreaName();
                        areaCoding = mLinkageCondition.getAreaCoding();
//                        weatherTypeXor = mLinkageCondition.getWeatherTypeXor();
                        weatherKeyValue = mLinkageCondition.getWeatherKeyValue();
                        latitude = mLinkageCondition.getLatitude();
                        longitude = mLinkageCondition.getLongitude();
                        scopeLong = mLinkageCondition.getScopeLong();
                        break;
                    }
                }
            }
        }
        updateView();
    }

    private void updateView(){
        if(TextUtils.isEmpty(areaName)){
            longitude = AppApplication.getInstance().getCurHouseInfo().getLongitude();
            latitude = AppApplication.getInstance().getCurHouseInfo().getLatitude();
            scopeLong = AppApplication.getInstance().getCurHouseInfo().getRange();
            areaName = AppApplication.getInstance().getCurHouseInfo().getProvince() + " " + AppApplication.getInstance().getCurHouseInfo().getCity() + " " + AppApplication.getInstance().getCurHouseInfo().getDistrict();
            areaCoding = AppApplication.getInstance().getCurHouseInfo().getDistrictId();
        }
        settingReferenceArea.setRightText(areaName);
        if(weatherKeyValue != null){
//            try {
//                JSONArray jsonArray = new JSONArray(weatherKeyValue);
//                List<WeatherValueBean> selectedWeatherValues = new ArrayList<>();
//                List<WeatherValueBean> weatherValues = new ArrayList<>();
//                StringBuilder stringBuilder = new StringBuilder();
//                for(int i=0; i<jsonArray.length(); i++){
////                    String name = jsonArray.getJSONObject(i).getString("Name");
//                    int value = jsonArray.getJSONObject(i).getInt("Value");
//                    if(weatherValues.size() == 0){
//                        out:
//                        for(WeatherTypeBean weatherTypeBean : weatherTypeList){
//                            for(WeatherValueBean weatherValueBean : weatherTypeBean.getValues()){
//                                if(weatherValueBean.getValue() == value){
//                                    weatherValues = weatherTypeBean.getValues();
//                                    selectedWeatherValues.add(new WeatherValueBean(value, weatherValueBean.getName()));
//                                    int res = getResources().getIdentifier(weatherValueBean.getName(), "string", getContext().getPackageName());
//                                    stringBuilder.append(getString(res)).append("、");
//                                    break out;
//                                }
//                            }
//                        }
//                    }else{
//                        for(WeatherValueBean weatherValueBean : weatherValues){
//                            if(weatherValueBean.getValue() == value){
//                                selectedWeatherValues.add(new WeatherValueBean(value, weatherValueBean.getName()));
//                                int res = getResources().getIdentifier(weatherValueBean.getName(), "string", getContext().getPackageName());
//                                stringBuilder.append(getString(res)).append("、");
//                                break;
//                            }
//                        }
//                    }
//                }
//                tvWeatherCondition.setText(getString(R.string.effective_when_time_holder, stringBuilder.substring(0, stringBuilder.length() - 1)));
//                selectedWeather.put(weatherTypeXor, selectedWeatherValues);
//                mWeatherTypeAdapter.checkSelected(weatherTypeXor);
//                if(weatherValues.size() > 1){
//                    mWeatherTypeAdapter.setSelectedValues(selectedWeatherValues);
//                }
//            } catch (JSONException e) {
//                e.printStackTrace();
//            }
            List<WeatherValueBean> selectedWeatherValues = new ArrayList<>();
            List<WeatherValueBean> weatherValues = new ArrayList<>();
            StringBuilder stringBuilder = new StringBuilder();
            for(WeatherValueBean weatherValue : weatherKeyValue){
                int value = weatherValue.getValue();
                if(weatherValues.size() == 0){
                    out:
                    for(WeatherTypeBean weatherTypeBean : weatherTypeList){
                        for(WeatherValueBean weatherValueBean : weatherTypeBean.getValues()){
                            if(weatherValueBean.getValue() == value){
                                weatherTypeXor = weatherTypeBean.getType();
                                weatherValues = weatherTypeBean.getValues();
                                selectedWeatherValues.add(new WeatherValueBean(value, weatherValueBean.getName()));
                                int res = getResources().getIdentifier(weatherValueBean.getName(), "string", getContext().getPackageName());
                                stringBuilder.append(getString(res)).append("、");
                                break out;
                            }
                        }
                    }
                }else{
                    for(WeatherValueBean weatherValueBean : weatherValues){
                        if(weatherValueBean.getValue() == value){
                            selectedWeatherValues.add(new WeatherValueBean(value, weatherValueBean.getName()));
                            int res = getResources().getIdentifier(weatherValueBean.getName(), "string", getContext().getPackageName());
                            stringBuilder.append(getString(res)).append("、");
                            break;
                        }
                    }
                }
            }
            tvWeatherCondition.setText(getString(R.string.effective_when_time_holder, stringBuilder.substring(0, stringBuilder.length() - 1)));
            selectedWeather.put(weatherTypeXor, selectedWeatherValues);
            mWeatherTypeAdapter.checkSelected(weatherTypeXor);
            if(weatherValues.size() > 1){
                mWeatherTypeAdapter.setSelectedValues(selectedWeatherValues);
            }
        }
    }

    @Override
    public void onRightClick(View view) {
        if(TextUtils.isEmpty(areaName)){
            toast(R.string.please_select_reference_area_hint);
            return;
        }
        if(selectedWeather.size() == 0){
            toast(R.string.please_select_specific_weather);
            return;
        }
        weatherTypeXor = selectedWeather.keyAt(0);
//        JsonArray jsonArray = new JsonArray();
//        for(WeatherValueBean weatherValueBean : selectedWeather.get(weatherTypeXor)){
//            JsonObject jsonObject = new JsonObject();
//            int strRes = getResources().getIdentifier(weatherValueBean.getName(), "string", getPackageName());
//            String name = getString(strRes);
//            jsonObject.addProperty("Name", name);
//            jsonObject.addProperty("Value", weatherValueBean.getValue());
//            jsonArray.add(jsonObject);
//        }
//        weatherKeyValue = jsonArray.toString();
        weatherKeyValue = selectedWeather.get(weatherTypeXor);
        //当前联动空，才去
        if(mLinkageCondition == null){
            //本地保存联动条件
            if(mLinkageBean == null){
                mLinkageBean = new LinkageBean();
                LinkageDataHolder.setLinkageData(mLinkageBean);
            }
            List<LinkageBean.LinkageCondition> linkageConditions = mLinkageBean.getLinkageConditions();
            if(linkageConditions == null){
                linkageConditions = new ArrayList<>();
            }
            mLinkageBean.setLinkageConditions(linkageConditions);
            mLinkageCondition = new LinkageBean.LinkageCondition();
            //先设置个本地的SerialNo，为了编辑找到对应的数据
            mLinkageCondition.setConditionSerialNo(UUID.randomUUID().toString());
            mLinkageCondition.setConditionType(4);
            linkageConditions.add(mLinkageCondition);
            mLinkageCondition.setSort(linkageConditions.indexOf(mLinkageCondition) + 1);
        }
        mLinkageCondition.setAreaType(2);
        mLinkageCondition.setAreaName(areaName);
        mLinkageCondition.setAreaCoding(areaCoding);
//        mLinkageCondition.setWeatherTypeXor(weatherTypeXor);
        mLinkageCondition.setWeatherKeyValue(weatherKeyValue);
        mLinkageCondition.setLongitude(longitude);
        mLinkageCondition.setLatitude(latitude);
        mLinkageCondition.setScopeLong(scopeLong);
        if(weatherTypeList != null){
            for(WeatherTypeBean weatherType : weatherTypeList){
                if(weatherType.getType() == weatherTypeXor){
                    mLinkageCondition.setImageUrl(weatherType.getImage());
                    break;
                }
            }
        }
        mLinkageCondition.setBriefing("天气");
        startActivity_SingleTask(EditLinkageActivity.class);
        finish();
    }

    @Override
    public void onClick(View view) {
//        showBottomDistrictDialog();
        Intent intent = new Intent(getContext(), LocationActivity.class);
        LocationData locationData = new LocationData();
        if(longitude > 0 && latitude > 0){
            locationData.location = longitude + ":" + latitude;
            locationData.scopeLong = scopeLong;
        }else{
            if (AppApplication.getInstance().getCurHouseInfo() != null) {
                locationData.location = AppApplication.getInstance().getCurHouseInfo().getLongitude() + ":" + AppApplication.getInstance().getCurHouseInfo().getLatitude();
            }
        }
        LocationActivity.startForResult(this, locationData, 1, LocationActivity.LOCATION_REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK){
            if (requestCode == LocationActivity.LOCATION_REQUEST_CODE) {
                LocationData locationData = (LocationData) data.getSerializableExtra("DATA");
                longitude = locationData.longitude;
                latitude = locationData.latitude;
                scopeLong = locationData.scopeLong;
                areaName = locationData.province + " " + locationData.city + " " + locationData.district;
                areaCoding = locationData.provinceId + locationData.cityId + locationData.districtId;
                settingReferenceArea.setRightText(areaName);
            }
        }
    }

    //    private BottomDistrictDialog mBottomDistrictDialog;
//    private void showBottomDistrictDialog(){
//        if (mBottomDistrictDialog == null) {
//            mBottomDistrictDialog = new BottomDistrictDialog(this);
//            mBottomDistrictDialog.setDialogClickListener(new BottomDistrictDialog.DialogClickListener() {
//                @Override
//                public void onConfirmClick(String text, String code) {
//                    areaName = text;
//                    areaCoding = code;
//                    settingReferenceArea.setRightText(areaName);
//                    mBottomDistrictDialog.dismiss();
//                }
//            });
//            new XPopup.Builder(this)
//                    .dismissOnBackPressed(true)
//                    .enableDrag(true)
//                    .asCustom(mBottomDistrictDialog);
//        }
//        mBottomDistrictDialog.show();
//    }

    private void showBottomCheckListDialog(List<WeatherValueBean> weatherValues) {
        if (mBottomCheckListDialog == null) {
            mBottomCheckListDialog = new BottomCheckListDialog(this);
            mBottomCheckListDialog.setDialogClickListener(new BottomCheckListDialog.DialogClickListener() {
                @Override
                public void onConfirmClick() {
                    WeatherValueAdapter adapter = (WeatherValueAdapter) mBottomCheckListDialog.getAdapter();
                    Map<Integer, WeatherValueBean> selected =  adapter.getSelected();
                    if(selected != null && selected.size() > 0){
                        selectedWeather.clear();
                        List<WeatherValueBean> selectedWeatherValues = new ArrayList<>();
                        StringBuilder stringBuilder = new StringBuilder();
                        for(int key : selected.keySet()){
                            selectedWeatherValues.add(selected.get(key));
                            int res = getResources().getIdentifier(selected.get(key).getName(), "string", getContext().getPackageName());
                            stringBuilder.append(getString(res)).append("、");
                        }
                        tvWeatherCondition.setText(getString(R.string.effective_when_time_holder, stringBuilder.substring(0, stringBuilder.length() - 1)));
                        mBottomCheckListDialog.dismiss();
                        selectedWeather.put(mClickWeatherType, selectedWeatherValues);
                        mWeatherTypeAdapter.checkSelected(mClickWeatherType);
                        if(adapter.getData().size() > 1){
                            mWeatherTypeAdapter.setSelectedValues(selectedWeatherValues);
                        }
                        getTitleBar().getRightView().setEnabled(true);
                    }else{
                        toast(R.string.please_select_specific_weather);
                        getTitleBar().getRightView().setEnabled(false);
                    }
                }
            });
            WeatherValueAdapter weatherValueAdapter = new WeatherValueAdapter(this);
            mBottomCheckListDialog.setAdapter(weatherValueAdapter);
            new XPopup.Builder(this)
                    .dismissOnBackPressed(true)
                    .enableDrag(true)
                    .asCustom(mBottomCheckListDialog);
        }
        WeatherValueAdapter weatherValueAdapter = (WeatherValueAdapter) mBottomCheckListDialog.getAdapter();
        weatherValueAdapter.setData(weatherValues);
        weatherValueAdapter.checked(selectedWeather.get(mClickWeatherType));
        mBottomCheckListDialog.show();
    }
}